Stack = require("./stack.js");
/**
 * -- 编写函数实现逆波兰表达式计算
 * 逆波兰表达式也叫后缀表达式，它将复杂表达式转换为可以依靠简单的操作得到计算结果的表达式，例如(a+b)*(c+d)转换为ab+cd+*
 * ["4", "13", "5", "/", "+"] 等价于(4 + (13 / 5)) = 6
 * ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] 等价于((10 * (6 / ((9 + 3) * -11))) + 17) + 5
 *
 * @author lmay.Zhou
 * @since 2019/4/7 23:09 星期日
 * @qq 379839355
 * @email lmay@lmaye.com
 */
function clacExp(exp) {
    // 初始化栈
    let stack = new Stack.Stack();

    for(let i=0; i<exp.length; ++i) {
        let item = exp[i];
        if(["+", "-", "*", "/"].indexOf(item) >= 0) {
            // 从栈顶弹出两个元素
            let x = stack.pop();
            let y = stack.pop();
            // 拼装表达式
            let cacl_exp = y + item + x;
            // 计算值，并取整
            let val = parseInt(eval(cacl_exp));
            // 将结果压入栈顶
            stack.push(val.toString());
        } else {
            // 否则把数值存入栈中
            stack.push(item);
        }
    }
    return stack.pop();
}

let exp_1 = ["4", "13", "5", "/", "+"];
let exp_2 = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"];
let exp_3 = [ '1', '4', '5', '+', '3', '+', '+', '3', '-', '9', '8', '+', '+' ];
console.log(clacExp(exp_1));
console.log(clacExp(exp_2));
console.log(clacExp(exp_3));